<template>
  <SearchForm :query="query" @search="onSearch" @reset="handleReset" />

  <n-space class="py-[10px]" justify="end">
    <n-button type="tertiary" size="small" @click="toggleAllExpand()">
      <template #icon>
        <n-icon depth="3" size="16"><ExpandRound /></n-icon>
      </template>
      展开/折叠
    </n-button>

    <n-button
      ghost
      type="primary"
      size="small"
      v-hasPermi="['system:menu:add']"
      @click="openDialog"
    >
      <template #icon>
        <n-icon size="18"><PlusRound /></n-icon>
      </template>
      新增
    </n-button>
  </n-space>

  <n-data-table
    :loading="loading"
    :columns="columns"
    :data="tableData"
    :row-key="(row: any) => row.menuId"
    :expanded-row-keys="expandedKeys"
    :children-key="'children'"
    striped
    @update:expanded-row-keys="expandedKeys = $event"
  />

  <UpdateMenuDialog :visible="visible" :data="data" @close="handleCloseDialog"></UpdateMenuDialog>

  <!-- <n-data-table
    :loading="loading"
    :columns="columns"
    :data="data"
    :pagination="{
      page: query.page,
      pageSize: query.pageSize,
      itemCount: total,
      showSizePicker: true,
      onUpdatePage: handlePageChange,
      onUpdatePageSize: handlePageSizeChange,
    }"
  /> -->
</template>

<script setup lang="tsx">
import { ref } from 'vue';
import SearchForm from './components/SearchForm.vue';
import { useTable } from '@/hooks/useTable';
import { NButton, NIcon, NSpace, useMessage } from 'naive-ui';
import { ExpandRound, PlusRound } from '@vicons/material';
import { deleteMenu, getMenuList } from '@/apis/system/menu';
import { handleTree } from '@/utils';
import UpdateMenuDialog from './components/UpdateMenuDialog.vue';
import { useDialog } from '@/hooks/useDialog';
import getColumns from './columns';

const message = useMessage();
const expandedKeys = ref<any[]>([]);
const queryMenuList = async (params: any) => {
  const res = await getMenuList(params);
  const data = handleTree(res.data, 'menuId');
  return { ...res, data };
};

const { query, tableData, loading, handleSearch, handleReset } = useTable({
  api: queryMenuList,
  defaultQuery: { menuName: null, status: null },
  pagination: false,
});

const { visible, data, openDialog, closeDialog } = useDialog();

// 查询表单提交
const onSearch = (values: any) => {
  Object.assign(query, values);
  handleSearch();
};

/**
 * 关闭弹窗回调
 * @param params
 */
const handleCloseDialog = (params: any) => {
  if (params?.needRefresh) {
    handleSearch();
  }
  closeDialog();
};

// 表格列定义
// columns moved to separate file: ./columns.tsx

function toggleAllExpand() {
  if (expandedKeys.value.length) {
    expandedKeys.value = [];
  } else {
    expandedKeys.value = collectAllKeys(tableData.value);
  }
}

async function handleDelete(row: any) {
  try {
    const res: any = await deleteMenu(row.menuId);
    if (res.code === 200) {
      message.success('删除成功');
      handleSearch();
    }
  } catch (error) {}
}

function collectAllKeys(tree: any) {
  const keys: any[] = [];
  const walk = (list: any) => {
    list.forEach((item: any) => {
      keys.push(item.menuId);
      if (item.children) walk(item.children);
    });
  };
  walk(tree);
  return keys;
}

// 从外部工厂函数生成 columns（需要 openDialog 和 handleDelete）
const columns = getColumns(openDialog, handleDelete);
</script>

<style scoped lang="less"></style>
